<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
          <navbar></navbar>
    </div>
    <!-- 面包屑导航 -->
    <div class="Box">
      <div class="table_tab">
        <div class="inquiry">
          <div class="headerbox">
            <div class="header">
              数据筛选
            </div>

          </div>
          <el-form
            :inline="true"
            ref="queryForm"
            :model="search"
            label-width=""
            size="mini"
          >
            <el-form-item label="平台">
              <el-select
                  v-model="search.platformId"
                  placeholder="请选择平台"
                  filterable
                  clearable
              >
                <el-option
                    v-for="item in platformList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                >
                </el-option>
              </el-select>
          </el-form-item>
            <el-form-item>
              <el-button
                @click="fetchData('search')"
                plain
                v-on:keyup.enter="fetchData('search')"
                type="primary"
                >搜索</el-button
              >
              <el-button plain @click="fetchData('reset')" type="primary">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="inquiryTab">
          <div class="inquiryTab_header">
            <div class="tabTitle">列表数据</div>
            <el-button
              @click="addClassify()"
              type="primary"
              v-if="parArray.indexOf('appNavigate_save') != -1"
              >新 增</el-button
            >
          </div>
          <div class="table">
           <matrix-table :dataList="manage.page.list" :config="manage.config" @receiveData="handlerSkip" :loading="loading" sortable></matrix-table>
             <div class="page" >
               <div class="block">
                  <el-pagination
                      @size-change="onSizeChange"
                      @current-change="onCurrentChange"
                      :current-page="manage.page.pageNo"
                      :page-size="manage.page.pageSize"
                      :page-sizes="[3, 5, 10, 20, 50]"
                      layout="total,sizes, prev, pager, next"
                      :total="manage.page.totalNum">
                  </el-pagination>
                </div>
             </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 新增下级对话框结束 -->
    <!-- 禁用类目时提示还有多少条数据 -->
    <el-dialog
        title="跳转设置"
        :visible.sync="dialogVisible"
        append-to-body
        width="30%"
        :before-close="handleClose">
        <div>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="主图:" prop="image">
                 <el-upload
                        v-if="ruleForm.image==''"
                        class="avatar-uploader"
                          ref="upload"
                          action="#"
                          :limit="1"
                          :on-exceed="test"
                          :before-upload="beforeAvatarUpload"
                          :http-request="imgUpload"
                          :file-list="fileListImg"
                          :show-file-list="false"
                          >
                          <!-- <img v-if="ImgHttps + scope.row.image" :src="ImgHttps + scope.row.image" class="avatar">-->
                          <i style="font-size:18px"  class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                          <div
                          v-else
                            style="
                              display: inline-block;
                              padding: 2px;
                              margin-right: 5px;
                              position: relative;
                            "
                          >
                            <img
                              v-image-preview
                              :src="ruleForm.image||ruleForm.image"
                              style="width: 90px; height: 90px;"
                            />
                            <i
                              @click="deleteImg()"
                              class="el-icon-error"
                              style="
                                position: absolute;
                                top: -5px;
                                right: -6px;
                                cursor: pointer;
                                z-index:999;
                                font-size:15px
                              "
                            ></i>
                          </div>

              </el-form-item>

               <el-form-item label="平台:"  prop="pingtai">
                <el-select
                style="width:80%"
                  v-model="ruleForm.pingtai"
                  placeholder="请选择平台"
                  multiple
              >
                <el-option
                    v-for="item in platformList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                >
                </el-option>
              </el-select>
              </el-form-item>
              <el-form-item label="名称:" prop="name">
                <el-input style="width:80%"  v-model="ruleForm.name"></el-input>
              </el-form-item>
               <el-form-item label="链接:" prop="url">
                <el-input style="width:80%"  v-model="ruleForm.url"></el-input>
              </el-form-item>
               <el-form-item label="排序:" prop="paixu" >
                <el-input style="width:80%" v-model="ruleForm.paixu" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"></el-input>
              </el-form-item>
              <el-form-item label="appId:" prop="appid">
                <el-input style="width:80%" v-model="ruleForm.appid"></el-input>
              </el-form-item>
               <el-form-item label="是否显示:">
                  <el-radio-group v-model="ruleForm.radio" style="width:80%">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
            </el-form>
        </div>
          <div class="btnClass">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="submit('ruleForm')">确 定</el-button>
          </div>
      </el-dialog>
  </div>
</template>

<script>
import MatrixTable from './components/MatrixTable.vue'
import common from './mixins/common'
import navbar from '@/components/navbar.vue'
export default {
  mixins: [common],
  watch: {

  },
  components: {
    MatrixTable,
    navbar
  },
  data () {
    return {
      fileListImg: [], // 上传图片
      ruleForm: {
        image: '', //
        name: '', //
        pingtai: '',
        url: '', //
        paixu: '', //
        radio: '',
        appid: ''
      },
      rules: {
        image: [
          { required: true, message: '请上传上传主图', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请填写名称', trigger: 'blur' }
        ],
        pingtai: [
          { required: true, message: '请选择平台', trigger: 'change' }
        ],
        url: [
          { required: true, message: '请填写链接', trigger: 'blur' }
        ],
        paixu: [
          { required: true, message: '请填写排序', trigger: 'blur' }
        ],
        appid: [
          { required: true, message: '请填写appId', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      manage: {
        page: { list: [], pageNo: 1, pageSize: 10, totalNum: 0, currentPage: 1 }, // 员工业绩统计(XX年XX月)
        sortObj: { prop: 'marketPrice', order: 'descending' }, // 排序
        config: [
          { prop: 'image', label: '主图', slot: 'mainImage' },
          { prop: 'platformName', label: '平台', slot: 'platformName' },
          { prop: 'name', label: '名称' },
          { prop: 'url', label: '链接' },
          { prop: 'sortNum', label: '排序', sortable: true },
          { prop: 'status', label: '是否显示', slot: 'isStatus' },
          { prop: 'updatedTime', label: '最后编辑时间' },
          { prop: 'soldNum', label: '操作', slot: 'operation' }
        ]
      },
      platformList: [], // 平台列表
      parArray: [],
      search: {
        platformId: ''
      },
      dialogType: '', // 弹框状态
      rowData: '', // 行数据
      loading: false

    }
  },
  mounted () {

  },
  created () {
    this.getPlatformList() // 获取平台列表
    this.fetchData()
    // 权限设定判断
    this.limits = JSON.parse(sessionStorage.getItem('limit'))
    const params = this.limits.buttonTreeDto.filter(
      (item) => item.menuCode === 'setSkipCode'// 菜单管理里面的菜单编码
    )
    params[0].buttonList.forEach((item) => {
      this.parArray.push(item.code)
    })
    console.log(this.parArray)
    // 权限设定判断
    document.onkeydown = (e) => {
      const key = window.event.keyCode
      if (key == 13) {
        this.searchEvent()
      }
    }
  },
  beforeRouteLeave (to, form, next) {
    document.onkeydown = null
    next()
  },

  methods: {
    // 校验 URL
    validURL (url) {
      const reg =
    /^(?!(ht|f)tps):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
      return reg.test(url)
    },
    submit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogType === 'edit') { // 编辑
            const params = {
              id: this.rowData.id,
              image: this.ruleForm.image,
              name: this.ruleForm.name,
              platformIds: this.ruleForm.pingtai,
              appId: this.ruleForm.appid,
              url: this.ruleForm.url,
              sortNum: this.ruleForm.paixu,
              status: this.ruleForm.radio
            }
            this.$api.matrixAppNavigateDetail(params).then((res) => {
              if (res.code == 0) {
                this.fetchData()
                this.$message.success('编辑成功')
                this.dialogVisible = false
              } else {
                this.dialogVisible = false
              }
            }).catch((err) => {
              console.log(err)
            })
          } else {
            const params = {
              image: this.ruleForm.image,
              name: this.ruleForm.name,
              platformIds: this.ruleForm.pingtai,
              appId: this.ruleForm.appid,
              url: this.ruleForm.url,
              sortNum: this.ruleForm.paixu,
              status: this.ruleForm.radio
            }
            this.$api.matrixAppNavigateDetail(params).then((res) => {
              if (res.code == 0) {
                this.fetchData()
                this.$message.success('新增成功')
                this.dialogVisible = false
              } else {
                this.dialogVisible = false
              }
            }).catch((err) => {
              console.log(err)
            })
          }
        }
      })
      // console.log(this.ruleForm)
    },
    handlerSkip (e) {
      console.log(e, 'eeeee')
      this.dialogType = 'edit'
      if (e.type === 'edit') {
        const platformList = []
        e.row.platformList.forEach((item) => {
          platformList.push(item.platformId)
        })
        this.ruleForm.image = e.row.image
        this.ruleForm.pingtai = platformList
        this.ruleForm.url = e.row.url
        this.ruleForm.name = e.row.name
        this.ruleForm.paixu = e.row.sortNum
        this.ruleForm.radio = e.row.status
        this.ruleForm.appid = e.row.appId
        this.rowData = e.row
        this.dialogVisible = true
      }
    },
    beforeAvatarUpload (file) {
      console.log(file, 'rwerwerwe')
      const isJPGorPNG = file.type === 'image/jpeg'
      const isPNGorPNG = file.type === 'image/png'
      // const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      console.log(isJPGorPNG, 'isJPG')
      // if (isJPGorPNG === false) {
      if (isJPGorPNG === 10000 || isPNGorPNG === 10000) { // 等于 10000 让这条件不成立
        this.$message.error('上传图片只能是 JPG 格式 或 PNG格式！')
        // this.$message.error('上传图片只能是 JPG或PNG 格式')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      // return isJPGorPNG && isLt2M
      return isLt2M
    },
    deleteImg () {
      this.ruleForm.image = ''
    },
    // 上传图片
    test () {
      this.$message.warning(
        '只能上传1张'
      )
    },
    imgUpload (response, index) {
      console.log(response, index, 'fileObj')
      // const length = this.form.fileListImg.length
      const formData = new FormData()
      formData.append('file', response.file)

      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.axios
        .post(
          '/sys/v1/common/upload/files?pathName=internalSystem',
          formData,
          config,
          {
            headers: {
              isLoading: false
            }
          }
        )
        .then((res) => {
          if (res.code == 0) {
            console.log(res.data.url, 'res')
            // this.imageUrl = res.data.url;
            // const obj = {
            //   img: res.data.url,
            //   creattime: new Date().toLocaleDateString()
            // }
            this.ruleForm.image = this.ImgHttps + res.data.url
          } else {
            this.$message.error(res.message)
          }
        })
    },
    // 新增调整设置
    addClassify () {
      this.dialogType = 'add'
      /*
      this.$nextTick(_ => {
        setTimeout(() => {
          this.$refs['ruleForm'].resetFields()
        }, 100)
      })
    */

      this.ruleForm.image = ''
      this.ruleForm.pingtai = ''
      this.ruleForm.url = ''
      this.ruleForm.name = ''
      this.ruleForm.paixu = ''
      this.ruleForm.radio = ''
      this.ruleForm.appid = ''
      this.$nextTick(_ => {
        this.$refs['ruleForm'].clearValidate()
        // this.$refs['ruleForm'].resetFields()
      })

      this.dialogVisible = true
    },
    handleClose () {
      this.dialogVisible = false
    },
    // 获取平台列表
    getPlatformList () {
      const params = {}
      this.$api.platformDataList(params).then((res) => {
        this.platformList = res.data
      }).catch((err) => {
        console.log(err)
      })
    },
    onSizeChange (sizeChange) {
      this.manage.page.pageNo = 1
      this.manage.page.currentPage = 1
      this.manage.page.pageSize = sizeChange
      this.fetchData()
    },
    onCurrentChange (currentChange) {
      this.manage.page.pageNo = currentChange
      this.fetchData()
    },
    fetchData (type) {
      this.loading = true
      if (type === 'reset') {
        this.manage.page.pageNo = 1
        this.manage.page.pageSize = 10
        this.manage.page.currentPage = 1
        this.search.platformId = ''
      }
      let params = {
        pageNo: this.manage.page.pageNo,
        pageSize: this.manage.page.pageSize,
        platformId: this.search.platformId
      }
      if (type === 'search') {
        this.manage.page.currentPage = 1
        this.manage.page.pageNo = 1
        params.pageNo = 1
        params = Object.assign({}, params, this.search)
        // 去除字符串 前后 空格
        for (const item in params) { if (typeof params[item] === 'string') { params[item] = params[item].trim() } }
      }
      this.$api.matrixAppNavigate(params).then((res) => {
        if (res.code === 0) {
          this.loading = false
          console.log(res)
          this.manage.page.list = res.data.list
          this.manage.page.totalNum = res.data.totalNum
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    checkValue (val, limit = 0) {
      val = val.replace(/[^\d.]/g, '') // 保留数字
      val = val.replace(/^00/, '0.') // 开头不能有两个0
      val = val.replace(/^\./g, '0.') // 开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') // 两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); // 只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : '' // 两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    }
  }
}
</script>
<style scoped lang="scss">
.Box {
  display: flex;
  justify-content: flex-start;
  width: 100%;

  .table_tab {
    width: 100%;
    margin-bottom: 50px;
  }
}
.table {
  border-radius: 5px;
  width: 100%;
}

.header {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-family: PingFang SC;
  font-weight: bold;
  color: #333333;
  padding-bottom: 10px;
}

.inquiry {
  background: #fff;
  padding: 10px 20px 10px 20px;
  border-radius: 5px;
  .el-form {
    margin-top: 10px;
  }
}
.inquiryTab {
  background: #fff;
  padding: 10px 20px 20px 20px;
  border-radius: 5px;
  .el-form {
    margin-top: 10px;
  }
  margin-top: 20px;
  .inquiryTab_header {
    display: flex;
    justify-content: space-between;
    /deep/ .el-button {
      height: 40px;
    }
  }
}

/deep/.el-table__expand-icon > .el-icon {
  color: transparent;
}

.table {
  margin-top: 10px;
  border: 1px solid #e8eaec;
  border-radius: 0;
  /deep/ .el-input--suffix .el-input__inner {
    // background: #409eff;
    color: #000;
    width: 104px;
    box-shadow: none;
  }
  /deep/ .el-button {
    padding: 10px 13px;
  }
}

.page {
  text-align: right;
  width: 100%;
  background: #f5f5f5;
  padding-right: 30px;
  position: fixed;
  bottom: 0px;
  right: 0px;
  z-index: 5;

  span {
    font-size: 14px;
    color: #666;
    display: inline-block;
    margin-left: 10px;
  }
  .el-pagination {
    display: inline-block;
    vertical-align: middle;
  }
}
/deep/.el-table__row:hover {
  color: rgb(45, 125, 223);
}
/deep/.el-dialog__header {
  padding: 20px 20px 20px 20px;
  font-family: PingFang SC;
  font-weight: bold;
  line-height: 25px;
  color: #333333;
}
/deep/.el-dialog {
  border-radius: 10px;
}
/deep/.el-dialog__headerbtn {
  top: 15px;
}
.headerbox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  border-bottom: 1px solid #ededed;
  padding-bottom: 10px;
}

.tabTitle {
  font-size: 18px;
  font-family: PingFang SC;
  font-weight: 400;
  line-height: 25px;
  color: #333333;
  opacity: 1;
  margin-top: 10px;
  margin-bottom: 20px;
}
/deep/.el-form-item__label {
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #333333;
}

/deep/ .el-dialog__footer {
  margin-top: -20px;
  padding-top: 20px;
}
/deep/.el-table thead {
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: bold;
  line-height: 22px;
  color: #333333;
  opacity: 1;
}

.btnClass{
  margin-top: 20px;
  display: flex;
  justify-content: right;
}
 :deep(.avatar-uploader .el-upload ){
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
  }
  .avatar {
    width: 90px;
    height: 90px;
    display: block;
  }
</style>
